package com.kczd.fragment;


import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.kczd.adapter.OrderPagerAdapter;
import com.kczd.client.R;
import com.kczd.entity.Location;
import com.kczd.util.Common;
import com.kczd.util.NetRET;
import com.kczd.view.NoScrollViewPager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


//订单页面
public class OrderFragment extends Fragment {
	
	private View view;
	private RadioGroup  order_rg;
	private RadioButton order_not_pay;//未支付订单
	private RadioButton order_finsh_pay;//已完成订单
	private RadioButton order_over_pay;//已取消订单
	
	private NoScrollViewPager vp_order;
	private OrderPagerAdapter vp_order_adapter;

	SweetAlertDialog pDialog = null;
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view=inflater.inflate(R.layout.fragment_order, null);
		if(Common.user != null)
		{
			new Thread(){  
				   @Override  
				   public void run()  
				   {  
						getOrder(Common.otype_1);//未支付
				   }  
			}.start();
		}
		
		setview();
		
		return view;
	}

	private void setview() {
		order_rg=(RadioGroup) view.findViewById(R.id.order_rg);
		order_not_pay =(RadioButton) view.findViewById(R.id.order_not_pay);
		order_finsh_pay=(RadioButton) view.findViewById(R.id.order_finsh_pay);
		order_over_pay =(RadioButton) view.findViewById(R.id.order_over_pay);
		vp_order=(NoScrollViewPager) view.findViewById(R.id.vp_order);
		vp_order_adapter = new OrderPagerAdapter(getFragmentManager());
		vp_order.setAdapter(vp_order_adapter);
		
		pDialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.PROGRESS_TYPE);
		pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
		pDialog.setTitleText("Loading");
		pDialog.setCancelable(false);
		
		vp_order.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
			   // TODO Auto-generated method stub
				switch (position) {
				case 0:
					order_not_pay.setChecked(true);
					break;
				case 1:
					order_finsh_pay.setChecked(true);
					break;
				case 2:
					order_over_pay.setChecked(true);
					break;
				}
			}
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub

			}
		});
		
		order_rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				switch (checkedId) {
				case R.id.order_not_pay:
					pDialog.show();
					new Thread(){  
					   @Override  
					   public void run()  
					   {  
							getOrder(Common.otype_1);//未支付
					   }  
					}.start();
					break;
				case R.id.order_finsh_pay:
					pDialog.show();
					new Thread(){  
						   @Override  
						   public void run()  
						   {  
								getOrder(Common.otype_5);//已完成
						   }  
						}.start();
					break;
				case R.id.order_over_pay:
					pDialog.show();
					new Thread(){  
						   @Override  
						   public void run()  
						   {  
								getOrder(Common.otype_0);//已取消
						   }  
						}.start();
					break;
				default:
					break;
				}
			}
		});
	}
	String url = Common.net_addr + "itf/tx_get_orders_info.php";
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Bundle data = msg.getData();
			String val = data.getString("ret_json");
			Log.e("zhangy","val的值是："+val);
			val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);
			String otype = data.getString("otype");
			JSONObject jsonResult;
			try {
				pDialog.dismiss();
				jsonResult = new JSONObject(val);
				if(otype.equals(Common.otype_1)){
					OrderNotFragment.orderNotlsit.clear();
				}else if(otype.equals(Common.otype_0)){
					OrderOverFragment.orderOverlsit.clear();
				}else if(otype.equals(Common.otype_5)){
					OrderFinishedFragment.orderFinishedlsit.clear();
				}
				// UI界面的更新等相关操作
				if(NetRET.NUM1.equals(jsonResult.getString("ret"))){
					JSONArray jsarr =  jsonResult.getJSONArray("list_Arr");
					if(jsonResult.getInt("ilist")==0){
						//Toast.makeText(getActivity(), "没有相关数据", Toast.LENGTH_SHORT).show();
					}else {
						for (int i = 0; i < jsonResult.getInt("ilist"); i++) {
							JSONObject jso = jsarr.getJSONObject(i);
							Location item = new Location();
							item.setDatetime(jso.getString("createTime"));
							item.setOrigin(jso.getString("oripos"));
							item.setTerminal(jso.getString("endpos"));
							item.setOkey(jso.getString("okey"));
							item.setU_name(jso.getString("driver_name"));
							item.setU_tel(jso.getString("driver_tel"));
							item.setU_img(jso.getString("driver_img"));
							item.setLink_pos(jso.getString("link_pos"));
							item.setTol_price(jso.getString("tol_price"));
							item.setLi(jso.getString("li"));
							item.setPrice_qibujia(jso.getString("price_qibujia"));
							item.setPrice_shichangfei(jso.getString("price_shichangfei"));
							item.setPrice_yuantufei(jso.getString("price_yuantufei"));
							item.setOrigin_lat(jso.getString("origin_lat"));
							item.setOrigin_lng(jso.getString("origin_lng"));
							item.setTerminal_lat(jso.getString("terminal_lat"));
							item.setTerminal_lng(jso.getString("terminal_lng"));
							if(jso.getString("taxiID")!=null) {
								item.setTaxiID(jso.getString("taxiID"));
							}
							if (otype.equals(Common.otype_1)) {
								//item.setType(R.mipmap.quxiao);
								OrderNotFragment.orderNotlsit.add(item);
							} else if (otype.equals(Common.otype_0)) {
								//item.setType(R.mipmap.phone_weizhifu);
								OrderOverFragment.orderOverlsit.add(item);
							} else if (otype.equals(Common.otype_5)) {
								//item.setType(R.mipmap.nothing);
								OrderFinishedFragment.orderFinishedlsit.add(item);
							}
						}

					}
					}else{
					Toast.makeText(getActivity(), jsonResult.getString("err"),
							Toast.LENGTH_SHORT).show();
				}
				if(otype.equals(Common.otype_1)){
					vp_order.setCurrentItem(0,false);
				}else if(otype.equals(Common.otype_5)){
					vp_order.setCurrentItem(1,false);
				}else if(otype.equals(Common.otype_0)){
					vp_order.setCurrentItem(2,false);
				}

				vp_order_adapter.notifyDataSetChanged();

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};

	public void getOrder(String otype) {

		//创建okHttpClient对象
		OkHttpClient client = new OkHttpClient();
		RequestBody requestBody = new FormBody.Builder()
				.add("otype", otype)
				.add("utype", Common.utype)
				.add("ukey", Common.user.getUkey())
				.build();
		Request request = new Request.Builder()
				.url(url)
				.post(requestBody)
				.build();
		try {
			Response response = client.newCall(request).execute();
			String strResult = response.body().string();
			Message msg = new Message();
			Bundle data = new Bundle();
			data.putString("ret_json", strResult);
			data.putString("otype", otype);
			msg.setData(data);
			handler.sendMessage(msg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
